package cn.edu.cqvie.ssm.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.File;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;


/**
 * 文件上传
 * 
 * @author zhengsh
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			SmartUpload smu = new SmartUpload();
			//初始化 SmartUpload 对象
			smu.initialize(getServletConfig(), request , response);
			//定义允许上传文件类型(可选设置项)
			smu.setAllowedFilesList("gif,jpg,doc,txt,xls,PNG,jpeg");
			//不允许上传文件类型(可选设置项)
			smu.setDeniedFilesList("exe,bat");
			//单个文件最大限制单位：B(可选设置项)
			smu.setMaxFileSize(1000000);
			//总共上传文件限制(可选设置项)
			smu.setTotalMaxFileSize(20000000);
			smu.setCharset("UTF-8");
			//执行上传
			smu.upload();
			File file = null;
			file = smu.getFiles().getFile(0);
			//文件存储路径
			String filePath = "";
			//webapp目录真实路径
			String rootPath =  getServletContext().getRealPath("/");
			if (!file.isMissing()) {
				//设置文件在服务器的保存位置
				filePath = "upload/";
				//文件路径和文件名
				filePath += file.getFileName();
				//文件另存到相对路径的文件夹中
				file.saveAs(rootPath + filePath, SmartUpload.SAVE_AUTO);
			}
			
			Request req = smu.getRequest();
			String username = req.getParameter("username");
			
			request.setAttribute("filePath", filePath);
			request.setAttribute("name", username);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.getRequestDispatcher("8_3/showfile.jsp").forward(request, response);
		
	}

	

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
